package com.hk.service.quartz;

import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.hk.commons.HqlFilter;
import com.hk.commons.JsonUtils;
import com.hk.commons.entity.Fundnavhistory;
import com.hk.commons.entity.yingmi.FundNav;
import com.hk.commons.utils.yingmi.YingmiApiUtils;
import com.hk.service.IFundNav;
import com.hk.service.IFundnavHistory;

public class FundNavQuartz extends BaseQuartz {

	private Logger logger = LoggerFactory.getLogger(FundNavQuartz.class);

	@Autowired
	public YingmiApiUtils utils;

	@Autowired
	public IFundNav fundNav;

	@Autowired
	public IFundnavHistory fundnavHis;

	@Override
	public void start() {

		String path = "/product/batchGetFundNav";

		Map<String, String> params = new HashMap<>();

		String result = utils.post(path, params);
		logger.info("fundNav is Quartz Task start time:{}......",
				System.currentTimeMillis());
		
		ExecutorService executor = Executors.newFixedThreadPool(1);
        Runnable task = new Runnable() {
            public void run() {
            	save(result);	
            }
        };
        executor.execute(task);
        executor.shutdown();		
	}

		
	private void save(String result){
		SimpleDateFormat sf = new SimpleDateFormat("YYYMMdd");
		try {
			List<FundNav> list = JsonUtils.toBean(result, List.class,
					FundNav.class);

			int size = list.size();
			for (int i = 0; i < size; i++) {
				Fundnavhistory fh = new Fundnavhistory();

				FundNav fn = list.get(i);
				fundNav.merge(fn);
				Date cs = fn.getNavDate();
				HqlFilter hq = new HqlFilter();
				hq.addEQFilter("fundCode", fn.getFundCode());
				hq.addEQFilter("navDate", cs != null ? sf.format(cs) : "");
				List<Fundnavhistory> fhList = fundnavHis.findByFilter(hq);
				if (fhList.size() == 0) {
					fh.setNavDate(fn.getNavDate() != null ? sf.format(fn
							.getNavDate()) : "");
					fh.setFundCode(fn.getFundCode());
					fh.setNav(fn.getNav());
					fh.setAccumulatedNav(fn.getAccumulatedNav());
					fh.setDayReturn(fn.getDayReturn());
					fh.setUnitYield(fn.getUnitYield());
					fh.setYearlyRoe(fn.getYearlyRoe());
					fundnavHis.add(fh);
				}
			}
		} catch (IOException e) {
			 e.printStackTrace();
		}

		logger.info("fundNav is Quartz Task end time:{}......",
				System.currentTimeMillis());

	}
	
}
